package com.fuqi.android.zhongcai.base.view.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.Button;
import com.fuqi.android.zhongcai.R;

public class CountDownButton extends Button {


    public CountDownButton(Context context) {
        super(context);
        init(context, null);
    }

    public CountDownButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CountDownButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private int countDownSeconds;

    protected void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CountDownButton, 0, 0);
        this.countDownSeconds = typedArray.getInt(R.styleable.CountDownButton_count_down_seconds, 60);
        typedArray.recycle();
        onCountListener = (CountDownDelegateListener) context;
    }

    class MyCount extends CountDownTimer {

        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            setEnabled(true);
            setClickable(true);
            setText("重新发送");
            onCountListener.onCountDownonFinished();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            onCountListener.onCountDown((int) (millisUntilFinished / 1000));
            setText(millisUntilFinished / 1000 + "秒后重发");
        }

    }

    public void countDown() {
        setEnabled(false);
        MyCount mc = new MyCount(countDownSeconds * 1000, 1000);
        mc.start();
    }


    private CountDownDelegateListener onCountListener;

    public interface CountDownDelegateListener {

        void onCountDown(int seconds);

        void onCountDownonFinished();
    }
}
